﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EasyMvvm;
using EasyNotepad.View;
using System.IO;

namespace EasyNotepad.ViewModel
{
    public class ShellViewModel : ObservableObject
    {

        IFileStorageService fileStorageService = ServiceLocator.Instance.Get<IFileStorageService>(true);
        StorageFile currentFile;

        private bool hasChanged = false;
        private string text = string.Empty;
        

        
        public string Text
        {
            get
            {
                return text;
            }
            set
            {
                text = value;
                hasChanged = true;
                OnPropertyChanged("Text");
            }
        }

        public void Open()
        {
            var file = fileStorageService.OpenFile();
            if (file != null)
            {
                file.Item2.Position = 0;
                using (StreamReader reader = new StreamReader(file.Item2))
                {
                    Text = reader.ReadToEnd();
                    hasChanged = false;
                }
                this.currentFile = file.Item1;
            }
        }

        public void New()
        {
            currentFile = null;
            Text = string.Empty;
            hasChanged = false;
        }

        public void SaveAs()
        {
            using (MemoryStream stream = new MemoryStream())
            {
                using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
                {
                    writer.Write(text);
                    writer.Flush();
                    StorageFile file = fileStorageService.SaveAs(stream);
                    if (file != null)
                    {
                        currentFile = file;
                        hasChanged = false;
                    }
                }
            }
        }

        public void Save()
        {
            if (currentFile == null)
            {
                SaveAs();
                return;
            }

            using (MemoryStream stream = new MemoryStream())
            {
                using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
                {
                    writer.Write(text);
                    writer.Flush();
                    StorageFile file = fileStorageService.Save(new Tuple<StorageFile,Stream>(currentFile, stream));
                    if (file != null)
                    {
                        currentFile = file;
                        hasChanged = false;
                    }
                }
            }
        }

        public void Close()
        {
            if (hasChanged)
            {
                //Ask if the user wants to save changes
            }
            App.Current.MainWindow.Close();
        }
    }
}
